/*
 * Copyright© 2003-2019 浙江汇信科技有限公司, All Rights Reserved.
 */
package com.icinfo.cloud.provider.punish.ucase.casemain.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.icinfo.cloud.common.security.util.UserUtil;
import com.icinfo.cloud.provider.common.constant.Constant;
import com.icinfo.cloud.provider.common.enums.*;
import com.icinfo.cloud.provider.common.exception.BusinessException;
import com.icinfo.cloud.provider.common.utils.BaseUtil;
import com.icinfo.cloud.provider.common.utils.SocialCreditCodeUtil;
import com.icinfo.cloud.provider.punish.api.vo.CasePartyRecordAdjustSaveReturnDto;
import com.icinfo.cloud.provider.punish.approval.service.ICaseApprovalWaitRecordService;
import com.icinfo.cloud.provider.punish.common.caseregister.service.IRegisterCommonService;
import com.icinfo.cloud.provider.punish.common.datareport.enums.CaseChangeOperationTypeEnum;
import com.icinfo.cloud.provider.punish.common.datareport.service.ICaseDataChangeReportRecordService;
import com.icinfo.cloud.provider.punish.common.documentoperate.dto.FillAndConvertToPdfRequest;
import com.icinfo.cloud.provider.punish.common.documentoperate.enums.DocumentRecordStatusEnum;
import com.icinfo.cloud.provider.punish.common.documentoperate.enums.DocumentStatusEnum;
import com.icinfo.cloud.provider.punish.common.documentoperate.service.IStageDocCommonOperateService;
import com.icinfo.cloud.provider.punish.config.model.ConfigBusiParamDocumentInfo;
import com.icinfo.cloud.provider.punish.config.model.SysDepartParam;
import com.icinfo.cloud.provider.punish.config.service.IConfigBusiParamDocumentInfoService;
import com.icinfo.cloud.provider.punish.config.service.ISysDepartParamService;
import com.icinfo.cloud.provider.punish.dataprocessing.mapper.DataProcessCaseMainDetailAuxiliaryInfoMapper;
import com.icinfo.cloud.provider.punish.dataprocessing.model.DataProcessCaseMainDetailAuxiliaryInfo;
import com.icinfo.cloud.provider.punish.evideinv.service.EvidenceInventoryService;
import com.icinfo.cloud.provider.punish.ucase.casemain.dto.*;
import com.icinfo.cloud.provider.punish.ucase.casemain.enums.*;
import com.icinfo.cloud.provider.punish.ucase.casemain.mapper.*;
import com.icinfo.cloud.provider.punish.ucase.casemain.model.*;
import com.icinfo.cloud.provider.punish.ucase.casemain.service.*;
import com.icinfo.cloud.provider.punish.ucase.casemain.vo.*;
import com.icinfo.cloud.provider.punish.ucase.caseregister.dto.CaseEmergencyReasonInfoDto;
import com.icinfo.cloud.workflow.work.dto.WorkFlowRollSubMainInfoAndRecordAdjustDto;
import com.icinfo.cloud.workflow.work.service.IWorkFlowRollSubMainInfoService;
import com.icinfo.cloud.xzcf.provider.member.userinfo.dto.UserDTO;
import com.icinfo.framework.core.service.support.MyBatisServiceSupport;
import com.icinfo.framework.mybatis.mapper.entity.Example;
import com.icinfo.framework.mybatis.pagehelper.page.PageMethod;
import com.icinfo.framework.tools.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 描述: 案件信息调整记录表 case_info_adjust_record 对应的Service接口实现类.<br>
 *
 * @author framework generator
 * @date 2022年06月16日
 */
@Service
@Slf4j
public class CaseInfoAdjustRecordServiceImpl extends MyBatisServiceSupport implements ICaseInfoAdjustRecordService {
    @Resource
    private CaseInfoAdjustRecordMapper caseInfoAdjustRecordMapper;
    @Resource
    private ICasePartiesRecordService casePartiesRecordService;
    @Resource
    private CasePartiesRecordMapper casePartiesRecordMapper;
    @Resource
    private CaseReasonMainRecordMapper caseReasonMainRecordMapper;
    @Resource
    private ICasePartiesLegalInfoService casePartiesLegalInfoService;
    @Resource
    private ICasePartiesPersonInfoService casePartiesPersonInfoService;
    @Resource
    private ICaseMainInfoService caseMainInfoService;
    @Resource
    private CaseAppendixRecordMapper caseAppendixRecordMapper;
    @Resource
    private CaseMainInfoMapper caseMainInfoMapper;
    @Resource
    private CaseMainDetailInfoMapper caseMainDetailInfoMapper;
    @Resource
    private IWorkFlowRollSubMainInfoService workFlowRollSubMainInfoService;
    @Resource
    private ICaseApprovalWaitRecordService caseApprovalWaitRecordService;
    @Resource
    private CaseMainDetailAuxiliaryInfoMapper caseMainDetailAuxiliaryInfoMapper;
    @Resource
    private EvidenceInventoryService evidenceInventoryService;
    @Resource
    private ICaseDataChangeReportRecordService caseDataChangeReportRecordService;
    @Resource
    private CaseDocumentRecordMapper caseDocumentRecordMapper;
    @Resource
    private ICaseDocumentRecordService caseDocumentRecordService;
    @Resource
    private IConfigBusiParamDocumentInfoService configBusiParamDocumentInfoService;
    @Resource
    private IStageDocCommonOperateService stageDocCommonOperateService;
    @Resource
    private CaseDocumentRecordHisMapper caseDocumentRecordHisMapper;
    @Resource
    private CasePartiesLegalInfoMapper casePartiesLegalInfoMapper;
    @Resource
    private CasePartiesPersonInfoMapper casePartiesPersonInfoMapper;
    @Resource
    private ISysDepartParamService sysDepartParamService;
    @Resource
    private ICaseReasonMainRecordService caseReasonMainRecordService;
    @Resource
    private IRegisterCommonService commonService;
    @Resource
    private DataProcessCaseMainDetailAuxiliaryInfoMapper dataProcessCaseMainDetailAuxiliaryInfoMapper;
    /**
     * 【V1.3.0】描述：获取案件信息调整分页记录
     *
     * @param request {@link CaseInfoAdjustRecordPageRequest} 分页请求对象
     * @return List<CaseInfoAdjustRecordVo> 案件信息调整分页记录
     * @author xiangyuyu
     * @date 2022-06-16 19:48
     */
    @Override
    public List<CaseInfoAdjustRecordVo> getCaseInfoAdjustPageList(CaseInfoAdjustRecordPageRequest request) {
        List<CaseInfoAdjustRecordVo> list = null;
        if (!ObjectUtils.isEmpty(request)) {
            PageMethod.startPage(request.getPageNum(), request.getLength(), request.getOrderBy());
            list = caseInfoAdjustRecordMapper.selectCaseInfoAdjustPageList(request);
        }
        if (ObjectUtils.isEmpty(list)) {
            list = new ArrayList<>();
        } else {
            list.forEach(e->{
                e.setAdjustTypeName(CaseInfoAdjustTypeEnum.getValueByCode(e.getAdjustType()));
                //获取附件信息
                String attachmentIds = e.getAttachmentId();
                List<CaseAttachmentInfoVo> attachmentList = new ArrayList<>();
                if(!ObjectUtils.isEmpty(attachmentIds)){
                    String[] ids = attachmentIds.split(Constant.STRING_COMMA);
                    for (String id : ids) {
                        CaseAppendixRecord record = caseAppendixRecordMapper.selectByPrimaryKey(id);
                        if(!ObjectUtils.isEmpty(record)){
                            CaseAttachmentInfoVo vo = new CaseAttachmentInfoVo();
                            BeanUtils.copyProperties(record,vo);
                            attachmentList.add(vo);
                        }
                    }
                }
                if(attachmentList.size() > 0){
                    e.setAttachmentList(attachmentList);
                }
            });
        }
        return list;
    }

    /**
     * 【V1.3.0】描述：保存案件信息调整记录
     *
     * @param saveDto {@link CaseInfoAdjustRecordDto}
     * @return int 保存成功记录数
     * @author xiangyuyu
     * @date 2022-06-16 19:48
     */
    @Override
    public int saveCaseInfoAdjustRecord(CaseInfoAdjustRecordDto saveDto) {
        log.info("saveCaseInfoAdjustRecord start ... saveDto:{}", saveDto);
        String operateType = saveDto.getOperateType();
        if (!RecordSaveTypeEnum.isLegalEnumCode(operateType)) {
            throw new BusinessException("请指定有效的操作类型(1-新增/2-修改)");
        }
        CaseInfoAdjustRecord caseInfoAdjustRecord = new CaseInfoAdjustRecord();
        if (!ObjectUtils.isEmpty(saveDto)) {
            BeanUtils.copyProperties(saveDto, caseInfoAdjustRecord);
        }
        String recordSaveType = saveDto.getOperateType();
        String id;
        //保存成功记录数
        int count;
        try {
            //机构信息获取
            UserDTO userInfo = UserUtil.getUserInfo();

            if(!ObjectUtils.isEmpty(userInfo)){
                String orgCode = userInfo.getOrgCode();
                String orgName = userInfo.getOrgName();
                caseInfoAdjustRecord.setAdjustOrgCode(orgCode);
                caseInfoAdjustRecord.setAdjustOrgName(orgName);
                if(ObjectUtils.isEmpty(orgCode) || ObjectUtils.isEmpty(orgName)){
                    throw new BusinessException("登录失效-未获取到机构编码等信息");
                }
            } else {
                throw new BusinessException("登录失效-saveCaseInfoAdjustRecord");
            }
            if (ObjectUtil.isEmpty(saveDto.getItemShowInfoAfterAdjust()) && ObjectUtil.isEmpty(saveDto.getItemShowInfoBeforeAdjust())){
                assembleAdjustInfo(caseInfoAdjustRecord);
            }
            if (RecordSaveTypeEnum.MOD.getCode().equals(recordSaveType)) {
                id = saveDto.getId();
                if (ObjectUtils.isEmpty(id)) {
                    throw new BusinessException(Constant.STRING_NO_PRIMARY_KEY);
                } else {
                    CaseInfoAdjustRecordRequest request = new CaseInfoAdjustRecordRequest(null, id);
                    List<CaseInfoAdjustRecordVo> list = getCaseInfoAdjustRecordList(request);
                    if (ObjectUtils.isEmpty(list) || list.size() == 0) {
                        throw new BusinessException("未匹配到调整记录信息");
                    }
                    Example updateE = new Example(SysDepartParam.class);
                    updateE.createCriteria().andEqualTo("id", id);
                    count = caseInfoAdjustRecordMapper.updateByExampleSelective(caseInfoAdjustRecord, updateE);
                }
            } else {
                id = BaseUtil.createUid();
                caseInfoAdjustRecord.setId(id);
                count = caseInfoAdjustRecordMapper.insertSelective(caseInfoAdjustRecord);

            }
        } catch (Exception e) {
            e.printStackTrace();
            if (e.getMessage().contains(Constant.STRING_DUPLICATE_ENTRY) ||
                    e.getMessage().contains(Constant.STRING_DUPLICATE_ENTRY_LOWER)) {
                throw new BusinessException("请勿重复添加");
            } else {
                throw e;
            }
        }
        log.info("saveCaseInfoAdjustRecord end");
        return count;
    }

    /**
     * 描述：组装调整信息
     *
     * @param record {@link CaseInfoAdjustRecord}
     * @author xiangyuyu
     * @date 2022-06-20 19:18
     */
    private void assembleAdjustInfo(CaseInfoAdjustRecord record) {
        String itemCodeBeforeAdjust = record.getItemCodeBeforeAdjust();
        String itemCodeAfterAdjust = record.getItemCodeAfterAdjust();
        String adjustType = record.getAdjustType();
        //组装变更前后
        List<String> itemCodeList = new ArrayList<>();
        itemCodeList.add(itemCodeBeforeAdjust);
        itemCodeList.add(itemCodeAfterAdjust);
        Example query;
        //变更前案由信息
        String itemShowInfoBefore = "";
        //变更后案由信息
        String itemShowInfoAfter = "";
        if (CaseInfoAdjustTypeEnum.CASE_REASON.getCode().equals(adjustType)) {
            query = new Example(CaseReasonMainRecord.class);
            query.createCriteria().andIn("id",itemCodeList);
            List<CaseReasonMainRecord> caseReasonMainRecords = caseReasonMainRecordMapper.selectByExample(query);

            for (CaseReasonMainRecord e : caseReasonMainRecords) {
                if (e.getCaseReasonCode().equals(itemCodeBeforeAdjust) && ObjectUtils.isEmpty(itemShowInfoBefore)) {
                    itemShowInfoBefore = e.getCaseReasonName();
                } else if (e.getCaseReasonCode().equals(itemCodeAfterAdjust) && ObjectUtils.isEmpty(itemShowInfoAfter)) {
                    itemShowInfoAfter = e.getCaseReasonName();
                }
            }
            record.setItemShowInfoBeforeAdjust(itemShowInfoBefore);
            record.setItemShowInfoAfterAdjust(itemShowInfoAfter);
        } else if (CaseInfoAdjustTypeEnum.PARTY.getCode().equals(adjustType)) {
            List<CasePartiesInfoVo> caseParties = casePartiesRecordService.getCasePartiesInfoList(new CasePartiesRecordQueryDto(record.getCaseId(), null,YesOrNoEnum.YES.getCode()));
            for (CasePartiesInfoVo e : caseParties) {
                String partyType = e.getPartyType();
                String partyId = e.getPartyId();
                String tmpStr;
                if(PartyTypeEnum.PERSON.getCode().equals(partyType)){
                    tmpStr = "姓名："+e.getPartyName()+" 证件号码："+e.getPartyIdentityCode()+" 联系电话："+e.getContactPhone()+" 住址："+e.getAddress()+" 工作单位："+e.getWorkUnitName();
                } else {
                    tmpStr = "单位名称："+e.getPartyName()+" 法定代表人姓名："+e.getLegalName()+" 统一社会信用代码："+e.getPartyIdentityCode()+" 注册地址："+e.getAddress();
                }
                if (partyId.equals(itemCodeBeforeAdjust) && ObjectUtils.isEmpty(itemShowInfoBefore)) {
                    itemShowInfoBefore = tmpStr;
                } else if(partyId.equals(itemCodeAfterAdjust) && ObjectUtils.isEmpty(itemShowInfoAfter)){
                    itemShowInfoAfter = tmpStr;
                }
            }
            record.setItemShowInfoBeforeAdjust(itemShowInfoBefore);
            record.setItemShowInfoAfterAdjust(itemShowInfoAfter);
        }
    }

    /**
     * 【V1.3.0】描述：查询案件信息调整记录
     *
     * @param request {@link CaseInfoAdjustRecordRequest}
     * @return Result<List < CaseInfoAdjustRecordVo>> 案件信息调整记录
     * @author xiangyuyu
     * @date 2022-06-16 19:48
     */
    @Override
    public List<CaseInfoAdjustRecordVo> getCaseInfoAdjustRecordList(CaseInfoAdjustRecordRequest request) {
        String caseId = request.getCaseId();
        String id = request.getId();
        Example query = new Example(CaseInfoAdjustRecord.class);
        Example.Criteria c = query.createCriteria();
        if (ObjectUtils.isEmpty(caseId)) {
            if (ObjectUtils.isEmpty(id)) {
                throw new BusinessException("请指定案件id或主键id后进行查询");
            } else {
                c.andEqualTo("id", id);
            }
        } else {
            c.andEqualTo("caseId", caseId);
        }
        List<CaseInfoAdjustRecord> list = caseInfoAdjustRecordMapper.selectByExample(query);
        List<CaseInfoAdjustRecordVo> returnList = new ArrayList<>();
        if (!ObjectUtils.isEmpty(list) && list.size() > 0) {
            list.forEach(e -> {
                CaseInfoAdjustRecordVo record = new CaseInfoAdjustRecordVo();
                BeanUtils.copyProperties(e, record);
                returnList.add(record);
            });

            returnList.forEach(e->{
                e.setAdjustTypeName(CaseInfoAdjustTypeEnum.getValueByCode(e.getAdjustType()));
                //获取附件信息
                String attachmentIds = e.getAttachmentId();
                List<CaseAttachmentInfoVo> attachmentList = new ArrayList<>();
                if(!ObjectUtils.isEmpty(attachmentIds)){
                    String[] ids = attachmentIds.split(Constant.STRING_COMMA);
                    for (String attachmentId : ids) {
                        CaseAppendixRecord record = caseAppendixRecordMapper.selectByPrimaryKey(attachmentId);
                        if(!ObjectUtils.isEmpty(record)){
                            CaseAttachmentInfoVo vo = new CaseAttachmentInfoVo();
                            BeanUtils.copyProperties(record,vo);
                            attachmentList.add(vo);
                        }
                    }
                }
                if(attachmentList.size() > 0){
                    e.setAttachmentList(attachmentList);
                }
            });
        }
        return returnList;
    }

    /**
     * 【V1.3.0】描述：保存当事人调整信息
     *
     * @param saveDto {@link CasePartyInfoAdjustDto}
     * @return int 保存成功记录数
     * @author xiangyuyu
     * @date 2022-06-16 19:48
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int saveAdjustInfoWithParty(CasePartyInfoAdjustDto saveDto) {
        UserDTO userInfo = UserUtil.getUserInfo();
        if(ObjectUtils.isEmpty(userInfo)){
            throw new BusinessException("登录失效 saveAdjustInfoWithParty");
        }
        //增加待审批时不允许调整限制
        String caseId = saveDto.getCaseId();
        int waitToApprovalCount = caseApprovalWaitRecordService.getWaitToApprovalCount(caseId);
        if(waitToApprovalCount > 0 ){
            throw new BusinessException("案件环节处于待审批状态时不允许调整当事人信息");
        }

        String partyIdBeforeAdjust = saveDto.getPartyIdBeforeAdjust();
        if (ObjectUtils.isEmpty(caseId)) {
            throw new BusinessException("请指定案件id");
        }
        //查询案件信息
        CaseMainInfoVo caseMainInfo = caseMainInfoService.getCaseMainInfo(caseId);
        //只有在调查取证阶段可以进行当事人信息调整操作
        String caseCurrentStageCode = caseMainInfo.getCaseCurrentStageCode();
        if(!Constant.STRING_STAGE_CODE_CASE_INVESTIGATION.equals(caseCurrentStageCode)){
            throw new BusinessException("该功能只允许案件处于调查取证阶段时操作");
        }
        //调整后的单位/个人信息至少一个不能为空
        CasePartiesLegalInfoDto casePartiesLegalInfo = saveDto.getCasePartiesLegalInfo();
        CasePartiesPersonInfoDto casePartiesPersonInfo = saveDto.getCasePartiesPersonInfo();
        if (ObjectUtils.isEmpty(casePartiesLegalInfo) && ObjectUtils.isEmpty(casePartiesPersonInfo)) {
            throw new BusinessException("调整后的单位/个人信息至少一个不能为空");
        }
        /*
            若调整后当事人证件号码或统一信用代码与本案件中其他当事人的证件号码或统一信用代码相同的，
            则提示用户“该当事人已存在！”，不允许修改。
         */
        //查询原当事人的信息（数据库查一遍是因为不能仅仅通过前端传数据去判断）
        CasePartiesRecordQueryDto queryDto = new CasePartiesRecordQueryDto(caseId, null,YesOrNoEnum.NO.getCode());
        List<CasePartiesInfoVo> casePartiesInfoList = casePartiesRecordService.getCasePartiesInfoList(queryDto);
        String partyTypeAfterAdjust = saveDto.getPartyTypeAfterAdjust();
        if (!PartyTypeEnum.isLegalEnumCode(partyTypeAfterAdjust)) {
            throw new BusinessException("请指定合法的'调整后的当事人类型'（1-个人/2-法人）");
        }
        //是否为合法当事人id
        boolean isLegalPartyId = false;
        //调整前后证件信息是否没有发生变化
        boolean isNewCertInfo = true;
        String certType = null;
        String certNo = null;
        //个人
        if (PartyTypeEnum.PERSON.getCode().equals(partyTypeAfterAdjust)) {
            //获取填写的个人信息
            if (ObjectUtils.isEmpty(casePartiesPersonInfo)) {
                throw new BusinessException("请指定调整后的当事人-个人信息");
            } else {
                //校验是否完善【粗略校验】，详细校验在当事人信息保存抽出的公共校验方法
                certType = casePartiesPersonInfo.getCertType();
                certNo = casePartiesPersonInfo.getCertNo();
                if (ObjectUtils.isEmpty(certType)) {
                    throw new BusinessException("未指定个人有效的证件类型");
                }
                if (ObjectUtils.isEmpty(certNo)) {
                    throw new BusinessException("未指定个人证件号码");
                }
            }
        } else if (PartyTypeEnum.LEGAL.getCode().equals(partyTypeAfterAdjust)) {
            certType = "统一社会信用代码";
            //获取填写的个人信息
            if (ObjectUtils.isEmpty(casePartiesLegalInfo)) {
                throw new BusinessException("请指定调整后的当事人-单位信息");
            } else {
                certNo = casePartiesLegalInfo.getUniscid();
                if (ObjectUtils.isEmpty(certNo)) {
                    throw new BusinessException("未指定单位有效的证件号码");
                }
            }
        }
        List<String> partyIdentityCodeList = new ArrayList<>();
        String certNoBeforeAdjust = null;
        String certTypeBeforeAdjust = "统一社会信用代码";
        String uuid = BaseUtil.createUid();
        for (CasePartiesInfoVo e : casePartiesInfoList) {
            String partyId = e.getPartyId();
            String partyIdentityType = ObjectUtils.isEmpty(e.getPartyIdentityType()) ? "统一社会信用代码" : e.getPartyIdentityType();
            String partyIdentityCode = e.getPartyIdentityCode();
            if (partyId.equals(partyIdBeforeAdjust) && YesOrNoEnum.YES.getCode().equals(e.getStatus())) {
                isLegalPartyId = true;
                certNoBeforeAdjust = partyIdentityCode;
                certTypeBeforeAdjust = partyIdentityType;
            }
            partyIdentityCodeList.add(partyIdentityType + uuid + partyIdentityCode);
        }
        if (!isLegalPartyId) {
            throw new BusinessException("无效当事人id");
        }
        String certTypeName = CertTypeEnum.getValueByCode(certType);
        //判断调整前后的证件信息是否相同
        if (certNo.equals(certNoBeforeAdjust) && certTypeName.equals(certTypeBeforeAdjust)) {
            isNewCertInfo = false;
        }

        if (isNewCertInfo) {
            if (partyIdentityCodeList.contains(certTypeName + uuid + certNo)) {
                throw new BusinessException("该当事人已存在！");
            }
        } else {
            int count = 0;
            for (String s : partyIdentityCodeList) {
                log.info("s:",s);
                String tmpStr = certTypeName + uuid + certNo;
                log.info("tmpStr:",tmpStr);
                if (s.equals(tmpStr)) {
                    count++;
                }
            }
            if (count >= 2) {
                throw new BusinessException("该当事人已存在！");
            }
        }
        //标记旧的当事人数据失效
        Example update = new Example(CasePartiesRecord.class);
        Example.Criteria c = update.createCriteria();
        c.andEqualTo("caseId", caseId);
        c.andEqualTo("partyId", partyIdBeforeAdjust);
        CasePartiesRecord casePartiesRecord = new CasePartiesRecord();
        casePartiesRecord.setStatus(YesOrNoEnum.NO.getCode());
        int updateCount = casePartiesRecordMapper.updateByExampleSelective(casePartiesRecord, update);

        int insertCount = 0;

        String partyIdUuid = BaseUtil.createUid();
        if (!isNewCertInfo) {
            partyIdUuid = partyIdBeforeAdjust;
        }
        CasePartiesRecordDto casePartiesRecordDto = new CasePartiesRecordDto();
        casePartiesRecordDto.setCaseId(caseId);
        casePartiesRecordDto.setId(BaseUtil.createUid());
        casePartiesRecordDto.setPartyId(partyIdUuid);
        //更新案件详情补充表
        CaseMainDetailAuxiliaryInfo updateCaseMainDetailAuxiliaryInfo=new CaseMainDetailAuxiliaryInfo();
        Example example=new Example(CaseMainDetailAuxiliaryInfo.class);
        example.createCriteria().andEqualTo("caseId",caseId).andEqualTo("partyId",partyIdBeforeAdjust);
        List<CaseMainDetailAuxiliaryInfo> caseMainDetailAuxiliaryInfos=caseMainDetailAuxiliaryInfoMapper.selectByExample(example);
        if(null!=caseMainDetailAuxiliaryInfos&&caseMainDetailAuxiliaryInfos.size()>0){
            updateCaseMainDetailAuxiliaryInfo.setId(caseMainDetailAuxiliaryInfos.get(0).getId());
            updateCaseMainDetailAuxiliaryInfo.setPartyId(partyIdUuid);
            if (PartyTypeEnum.PERSON.getCode().equals(partyTypeAfterAdjust)) {
                updateCaseMainDetailAuxiliaryInfo.setPartyName(casePartiesPersonInfo.getName());
            }else if(PartyTypeEnum.LEGAL.getCode().equals(partyTypeAfterAdjust)){
                updateCaseMainDetailAuxiliaryInfo.setPartyName(casePartiesLegalInfo.getEntName());
            }
            caseMainDetailAuxiliaryInfoMapper.updateByPrimaryKeySelective(updateCaseMainDetailAuxiliaryInfo);
        }
        //保存当事人信息
        if (PartyTypeEnum.PERSON.getCode().equals(partyTypeAfterAdjust)) {
            casePartiesPersonInfo.setCaseId(caseId);
            casePartiesPersonInfo.setId(partyIdUuid);
            casePartiesPersonInfo.setOperateType(isNewCertInfo?RecordSaveTypeEnum.ADD.getCode():RecordSaveTypeEnum.MOD.getCode());
            casePartiesPersonInfo.setIsQueryInvalidData(YesOrNoEnum.YES.getCode());
            insertCount = casePartiesPersonInfoService.saveCasePartiesPersonInfo(casePartiesPersonInfo);
            casePartiesRecordDto.setAddressAreas(casePartiesPersonInfo.getAddressAreasStr());
            casePartiesRecordDto.setAddressDetail(casePartiesPersonInfo.getAddressDetail());
            casePartiesRecordDto.setPartyIdentityCode(casePartiesPersonInfo.getCertNo());
            casePartiesRecordDto.setPartyIdentityType(casePartiesPersonInfo.getCertType());
            casePartiesRecordDto.setPartyName(casePartiesPersonInfo.getName());
            casePartiesRecordDto.setPartyType(PartyTypeEnum.PERSON.getCode());

        } else if (PartyTypeEnum.LEGAL.getCode().equals(partyTypeAfterAdjust)) {
            casePartiesLegalInfo.setCaseId(caseId);
            casePartiesLegalInfo.setId(partyIdUuid);
            casePartiesLegalInfo.setOperateType(isNewCertInfo?RecordSaveTypeEnum.ADD.getCode():RecordSaveTypeEnum.MOD.getCode());
            casePartiesLegalInfo.setIsQueryInvalidData(YesOrNoEnum.YES.getCode());
            casePartiesLegalInfo.setLegalIndustryType(casePartiesLegalInfo.getLegalIndustryType());
            insertCount = casePartiesLegalInfoService.saveCasePartiesLegalInfo(casePartiesLegalInfo);
            casePartiesRecordDto.setPartyIdentityCode(casePartiesLegalInfo.getUniscid());
            casePartiesRecordDto.setPartyName(casePartiesLegalInfo.getEntName());
            casePartiesRecordDto.setPartyType(PartyTypeEnum.LEGAL.getCode());
            casePartiesRecordDto.setPartyIdentityType(null);
        }
        log.info("insertCount:{}",insertCount);

        int saveCount = casePartiesRecordService.saveCasePartiesInfo(casePartiesRecordDto);
        log.info("saveCount:{}",saveCount);
        //保存附件信息
        List<CaseAttachmentInfoSaveDto> attachmentInfoList = saveDto.getAttachmentInfo();
        String finalPartyId = partyIdUuid;
        //附件id（多个逗号分隔）
        StringBuilder attachmentIdSb = new StringBuilder();
        attachmentInfoList.forEach(e -> {
            CaseAppendixRecord caseAppendixRecord = new CaseAppendixRecord();
            String attachmentId = e.getId();
            if (ObjectUtils.isEmpty(attachmentId)) {
                BeanUtils.copyProperties(e, caseAppendixRecord);
                attachmentId = BaseUtil.createUid();
                attachmentIdSb.append(attachmentId+Constant.STRING_COMMA);
                caseAppendixRecord.setId(attachmentId);
                caseAppendixRecord.setCaseId(saveDto.getCaseId());
                caseAppendixRecord.setCaseStageName(caseMainInfo.getCaseCurrentStageName());
                caseAppendixRecord.setCaseStageCode(caseMainInfo.getCaseCurrentStageCode());
                caseAppendixRecord.setCaseLinkCode(caseMainInfo.getCaseCurrentLinkCode());
                caseAppendixRecord.setCaseLinkName(caseMainInfo.getCaseCurrentLinkName());

                if (!ObjectUtils.isEmpty(userInfo)) {
                    caseAppendixRecord.setUploadUserId(userInfo.getUserId() + "");
                    caseAppendixRecord.setUploadUserName(userInfo.getRealName());
                }
                caseAppendixRecord.setUploadTime(LocalDateTime.now());
                String appendixTypeId = caseAppendixRecord.getAppendixTypeId();
                if (ObjectUtils.isEmpty(appendixTypeId)) {
                    throw new BusinessException("未指定附件类型id【" + caseAppendixRecord.getAppendixName() + "】");
                }
                String appendixUrl = caseAppendixRecord.getAppendixUrl();
                if (ObjectUtils.isEmpty(appendixUrl)) {
                    throw new BusinessException("未指定附件地址【" + caseAppendixRecord.getAppendixName() + "】");
                }
                caseAppendixRecord.setPartyId(finalPartyId);
                caseAppendixRecordMapper.insertSelective(caseAppendixRecord);
            }
        });

        //更新案件名称
        //String caseName = saveDto.getCaseName();
        updateCaseNameInfo(caseId);

        CaseInfoAdjustRecordDto caseInfoAdjustRecordDto = new CaseInfoAdjustRecordDto();
        caseInfoAdjustRecordDto.setOperateType(RecordSaveTypeEnum.ADD.getCode());
        caseInfoAdjustRecordDto.setCaseId(caseId);
        caseInfoAdjustRecordDto.setAdjustType(CaseInfoAdjustTypeEnum.PARTY.getCode());
        caseInfoAdjustRecordDto.setItemCodeBeforeAdjust(partyIdBeforeAdjust);
        caseInfoAdjustRecordDto.setItemCodeAfterAdjust(finalPartyId);
        caseInfoAdjustRecordDto.setAdjustReason(saveDto.getAdjustReason());
        caseInfoAdjustRecordDto.setAttachmentInfo(saveDto.getAttachmentInfo());
        caseInfoAdjustRecordDto.setAdjustUserId(userInfo.getUserId()+"");
        caseInfoAdjustRecordDto.setAdjustUserName(userInfo.getRealName());

        String attachmentIds = attachmentIdSb.toString();
        if(!ObjectUtils.isEmpty(attachmentIds)){
            caseInfoAdjustRecordDto.setAttachmentId(attachmentIds.substring(0,attachmentIds.length()-1));
        }
        saveCaseInfoAdjustRecord(caseInfoAdjustRecordDto);
        if(!partyIdBeforeAdjust.equals(partyIdUuid)){
            workFlowRollSubMainInfoService.doModWorkFlowRollSubMainInfoAndRecord(caseId,partyIdBeforeAdjust,partyIdUuid);
        }
        //同步更新证据库当事人信息
        try {
            evidenceInventoryService.updateCpInfo(saveDto.getCaseId());
        }catch (Exception e){
            log.info("证据库更新当事人失败:{}",e.getMessage());
        }
        if ((saveCount == insertCount) && insertCount == 1) {
            //当事人更新成功后，生成一条记录，然后定时重新上报已经上报成功的数据
            caseDataChangeReportRecordService.save(caseId, CaseChangeOperationTypeEnum.OPERATION_TYPE_1.getCode(), String.valueOf(userInfo.getUserId()));
            return Constant.INTEGER_1;
        } else {
            log.warn("saveCount:{},insertCount:{}", saveCount, insertCount);
            throw new BusinessException("更新当事人信息时出现异常");
        }
    }

    /**
     * 描述：更新案件名称等信息
     *
     * @param caseId      案件id
     * @return int 更新记录数
     * @author xiangyuyu
     * @date 2022-06-29 16:14
     */
    private int updateCaseNameInfo(String caseId) {
        //后台自动生成案件名称
        //去除案由中的“对”和“的行政处罚”
        //多当事人  `${party}等${partyCount}个当事人涉嫌${resetReason}案`
        //多案由    `${party}涉嫌${resetReason}等${caseLen}项违法行为案`
        //单当事人  `${party}涉嫌${resetReason}案`

        //获取当事人信息
        List<CasePartiesRecordVo> casePartiesInfoList = casePartiesRecordService.getCasePartiesInfo(caseId);
        CasePartiesRecordVo theFirstPartyInfo = casePartiesInfoList.get(Constant.INTEGER_0);
        String partyShowName = theFirstPartyInfo.getPartyName();
        int partyNum = casePartiesInfoList.size();
        if(partyNum > 1){
            partyShowName += "等"+partyNum+"个当事人";
        }

        //获取案由信息
        String caseReasonName = "";
        Example example = new Example(CaseReasonMainRecord.class);
        example.createCriteria().andEqualTo("caseId", caseId).andEqualTo("status", Constant.STRING_1);
        List<CaseReasonMainRecord> caseReasonMainRecords = caseReasonMainRecordMapper.selectByExample(example);
        if (!ObjectUtils.isEmpty(caseReasonMainRecords)) {
            if (caseReasonMainRecords.size() == 1) {
                caseReasonName = BaseUtil.handleCaseReason(caseReasonMainRecords.get(0).getCaseReasonName() + "案");
            } else {
                caseReasonName = BaseUtil.handleCaseReason(caseReasonMainRecords.get(0).getCaseReasonName()) + "等" + caseReasonMainRecords.size() + "项违法行为案";
            }
        }

        String newCaseName = partyShowName + "涉嫌" + caseReasonName;

        int count;
        CaseMainInfo caseMainInfo = new CaseMainInfo();
        caseMainInfo.setId(caseId);
        caseMainInfo.setCaseName(newCaseName);
        count = caseMainInfoMapper.updateByPrimaryKeySelective(caseMainInfo);

        CaseMainDetailInfo caseMainDetailInfo = new CaseMainDetailInfo();
        caseMainDetailInfo.setCaseId(caseId);
        caseMainDetailInfo.setCaseName(newCaseName);
        caseMainDetailInfoMapper.updateByPrimaryKeySelective(caseMainDetailInfo);
        return count;
    }

    /**
     * 【V1.4.1】描述： 保存案由调整记录
     *
     * @author: zhengqiang
     * @date: 2022/8/23
     * @param: saveDto
     * @return {@link int}
     **/
    @Override
    public int saveAdjustInfoWithCaseReason(CaseReasonInfoAdjustDto saveDto) {
        //暂时不校验
        //ValidateUtil.validThrowException(saveDto);
        UserDTO userInfo = UserUtil.getUserInfo();
        if (ObjectUtils.isEmpty(userInfo)) {
            throw new BusinessException("登录失效 saveAdjustInfoWithCaseReason");
        }
        CaseInfoAdjustRecord caseInfoAdjustRecord = new CaseInfoAdjustRecord();
        caseInfoAdjustRecord.setCaseId(saveDto.getCaseId());
        caseInfoAdjustRecord.setAdjustType(CaseInfoAdjustTypeEnum.CASE_REASON.getCode());
        caseInfoAdjustRecord.setItemCodeBeforeAdjust(saveDto.getCaseReasonCodeBeforeAdjust());
        caseInfoAdjustRecord.setItemShowInfoBeforeAdjust(saveDto.getCaseReasonBeforeAdjust());
        caseInfoAdjustRecord.setItemCodeAfterAdjust(saveDto.getCaseReasonCodeAfterAdjust());
        caseInfoAdjustRecord.setItemShowInfoAfterAdjust(saveDto.getCaseReasonAfterAdjust());
        caseInfoAdjustRecord.setAdjustUserId(userInfo.getUserId()+"");
        caseInfoAdjustRecord.setAdjustUserName(userInfo.getRealName());
        caseInfoAdjustRecord.setAdjustOrgCode(userInfo.getOrgCode());
        caseInfoAdjustRecord.setAdjustOrgName(userInfo.getOrgName());
        caseInfoAdjustRecord.setId(BaseUtil.createUid());
        return caseInfoAdjustRecordMapper.insertSelective(caseInfoAdjustRecord);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public CasePartyRecordAdjustSaveReturnDto saveAdjustPartyRecord(CasePartyRecordAdjustSaveDto saveDto) {
        String caseId = saveDto.getCaseId();
        CaseMainInfoVo caseMainInfo = caseMainInfoService.getCaseMainInfo(caseId);
        //1.参数校验
        String message = checkAndAssembleAdjustPartyRecordParam(caseMainInfo, saveDto);
        if (!StringUtils.isEmpty(message)) {
            throw new BusinessException(message);
        }

        CasePartyRecordAdjustSaveReturnDto returnDto = dealAdjustPartyRecordForDocument(saveDto, caseMainInfo);
        return returnDto;
    }


    /**
     * 描述：保存调整当事人信息 --处理调整当事人，文书记录信息
     *
     * @param saveDto      保存dto
     * @param caseMainInfo 案例主要信息
     * @return {@link CasePartyRecordAdjustSaveReturnDto }
     * @author shishengyao
     * @date 2023/03/25
     */
    private CasePartyRecordAdjustSaveReturnDto dealAdjustPartyRecordForDocument(CasePartyRecordAdjustSaveDto saveDto,CaseMainInfoVo caseMainInfo) {
        //机构信息获取
        UserDTO userInfo = UserUtil.getUserInfo();
        ConfigBusiParamDocumentInfo configBusiParamDocumentInfo = configBusiParamDocumentInfoService.getDocumentInfoByDocumentKindCode(caseMainInfo.getBusiParamId(), DocumentKindEnum.DOC_KIND_DK1TZDSRNBSPB.getCode());
        CasePartyRecordAdjustSaveReturnDto returnDto= new CasePartyRecordAdjustSaveReturnDto();
        CaseDocumentRecordDto caseDocumentRecordDto = caseDocumentRecordService.getCaseDocumentRecordByKindCode(saveDto.getCaseId(), DocumentKindEnum.DOC_KIND_DK1TZDSRNBSPB.getCode());
        String documentId=saveDto.getDocumentId();
        //校验是否有未完成的调整当事人申请
        if (ObjectUtil.isNotEmpty(caseDocumentRecordDto) && !DocumentStatusEnum.CHECK_END.getCode().equals(caseDocumentRecordDto.getDocumentApprovalStatus())){
            if (!caseDocumentRecordDto.getId().equals(saveDto.getDocumentId())){
                throw new BusinessException("存在未完成的调整当事人申请，请完成后再提交新的申请");
            }else if (DocumentStatusEnum.CHECKING.getCode().equals(caseDocumentRecordDto.getDocumentApprovalStatus())){
                throw new BusinessException("调整当事人申请正在审判中，请在审批之后再提交新的申请");
            }
        }
        CaseDocumentRecordVo recordInfo=null;
        if (ObjectUtil.isNotEmpty(documentId)) {
            recordInfo = caseDocumentRecordService.getCaseDocumentRecordInfo(saveDto.getDocumentId());
            //防止前端随便传documentId导致数据异常，再次校验
            if (ObjectUtil.isNotEmpty(recordInfo) && DocumentStatusEnum.CHECK_END.getCode().equals(caseDocumentRecordDto.getDocumentApprovalStatus())) {
                documentId = "";
            } else if (ObjectUtil.isNotEmpty(recordInfo) && !DocumentStatusEnum.CHECK_END.getCode().equals(recordInfo.getDocumentApprovalStatus())) {
                //校验是否有未完成的调整当事人申请
                if (!caseDocumentRecordDto.getId().equals(saveDto.getDocumentId())) {
                    throw new BusinessException("存在未完成的调整当事人申请，请完成后再提交新的申请");
                } else if (DocumentStatusEnum.CHECKING.getCode().equals(caseDocumentRecordDto.getDocumentRecordStatus())) {
                    throw new BusinessException("调整当事人申请正在审判中，请在审批之后再提交新的申请");
                }
            }
        }

        CaseDocumentRecord caseDocumentRecord = new CaseDocumentRecord();
        //设置文书为暂存状态
        if (RecordSaveTypeEnum.TEMP.getCode().equals(saveDto.getOperateType())){
            caseDocumentRecord.setDocumentRecordStatus(DocumentRecordStatusEnum.DRAFT.getCode());
        }else {
            FillAndConvertToPdfRequest pdfRequest = new FillAndConvertToPdfRequest();
            pdfRequest.setTemplateCode(configBusiParamDocumentInfo.getTemplatePersonCode());
            pdfRequest.setParamMap(BaseUtil.javaToMap(saveDto));

            Map<String, String> pdfUrl = stageDocCommonOperateService.getConvertedPdfUrl(pdfRequest);
            String fileUrl = pdfUrl.get("fileUrl");
            caseDocumentRecord.setDocumentRecordStatus(DocumentRecordStatusEnum.NORMAL.getCode());
            caseDocumentRecord.setDocumentUrl(fileUrl);
        }

        caseDocumentRecord.setDocumentContent(JSONObject.toJSONString(saveDto));
        caseDocumentRecord.setDocumentTemplateCode(configBusiParamDocumentInfo.getTemplatePersonCode());
        caseDocumentRecord.setDocumentUrlAfterSeal("");
        caseDocumentRecord.setDocumentUrlAfterSeal("");
        //生成默认待提交状态
        if ("1".equals(configBusiParamDocumentInfo.getIsApprove())) {
            caseDocumentRecord.setDocumentApprovalStatus(DocumentStatusEnum.WAIT_TO_SUBMIT.getCode());
            caseDocumentRecord.setDocumentAuditStatus("notSubmit");
        }

        caseDocumentRecord.setCreateUserName(userInfo.getRealName());
        caseDocumentRecord.setCreateUserId(userInfo.getUserId().toString());
        caseDocumentRecord.setDocumentCatalogCode(configBusiParamDocumentInfo.getDocumentCatalogCode());
        caseDocumentRecord.setPartyId("");
        if (ObjectUtil.isNotEmpty(documentId)) {
            //添加历史
            CaseDocumentRecordHis caseDocumentRecordHis = new CaseDocumentRecordHis();
            BeanUtils.copyProperties(recordInfo, caseDocumentRecordHis);
            //增加创建时间设置
            try {
                Date createTime = Date.from(recordInfo.getDocumentCreateTime().atZone(ZoneId.systemDefault()).toInstant());
                caseDocumentRecordHis.setDocumentCreateTime(createTime);
            } catch (Exception e) { }
            caseDocumentRecordHis.setId(StringUtils.uuid());
            caseDocumentRecordHis.setRecordId(saveDto.getDocumentId());
            caseDocumentRecordHis.setOp("update");
            caseDocumentRecordHis.setHisCreateTime(new Date());
            caseDocumentRecordHisMapper.insert(caseDocumentRecordHis);

            caseDocumentRecord.setId(saveDto.getDocumentId());
            caseDocumentRecordMapper.updateByPrimaryKeySelective(caseDocumentRecord);
        } else {
//            List<CasePartiesRecordVo> casePartiesInfo = casePartiesRecordService.getCasePartiesInfo(caseMainInfo.getId());
//            String partyId = casePartiesInfo.stream().map(p -> p.getPartyId()).collect(Collectors.joining(","));
//            caseDocumentRecord.setPartyId(partyId);
            caseDocumentRecord.setCaseId(caseMainInfo.getId());
            caseDocumentRecord.setDocumentCreateTime(LocalDateTime.now());
            caseDocumentRecord.setCaseStageName(caseMainInfo.getCaseCurrentStageName());
            caseDocumentRecord.setCaseStageCode(caseMainInfo.getCaseCurrentStageCode());
            caseDocumentRecord.setCaseLinkCode(caseMainInfo.getCaseCurrentLinkCode());
            caseDocumentRecord.setCaseLinkName(caseMainInfo.getCaseCurrentLinkName());
            caseDocumentRecord.setId(StringUtils.uuid());
            caseDocumentRecord.setDocumentCreateTime(LocalDateTime.now());
            caseDocumentRecordMapper.insertSelective(caseDocumentRecord);
        }
        returnDto.setDocumentId(caseDocumentRecord.getId());
        returnDto.setDocumentCatalogCode(caseDocumentRecord.getDocumentCatalogCode());
        return returnDto;
    }


    /**
     * 描述：审批通过之后更新调整当事人信息
     *
     * @param documentId 文档id
     * @return {@link CasePartyRecordAdjustSaveReturnDto }
     * @author shishengyao
     * @date 2023/03/21
     */
    @Override
    @Transactional(rollbackFor = {Error.class, Exception.class})
    public int updateAdjustPartyRecordAfterApproval(String documentId) {
        UserDTO userInfo = UserUtil.getUserInfo();
        if (ObjectUtils.isEmpty(userInfo)) {
            throw new BusinessException("登录失效 updateAdjustPartyRecordAfterApproval");
        }

        CaseDocumentRecord caseDocumentRecord = caseDocumentRecordMapper.selectByPrimaryKey(documentId);
        CaseMainInfoVo caseMainInfo = caseMainInfoService.getCaseMainInfo(caseDocumentRecord.getCaseId());
        String caseId = caseMainInfo.getId();
        // 1、使其他调整当事人文书失效
        Example invalidExample =new Example(CaseDocumentRecord.class);
        invalidExample.createCriteria().andEqualTo("caseId",caseId)
                .andEqualTo("documentCatalogCode",caseDocumentRecord.getDocumentCatalogCode())
                .andEqualTo("documentRecordStatus", DocumentRecordStatusEnum.NORMAL.getCode())
                .andNotEqualTo("id",documentId);
        CaseDocumentRecord invalidRecord=new CaseDocumentRecord();
        invalidRecord.setDocumentRecordStatus(DocumentRecordStatusEnum.INVALID.getCode());
        caseDocumentRecordMapper.updateByExampleSelective(invalidRecord,invalidExample);

        String documentContent = caseDocumentRecord.getDocumentContent();
        JSONObject jsonObj = JSONObject.parseObject(documentContent);
        CasePartyRecordAdjustSaveDto saveDto = JSON.toJavaObject(jsonObj,CasePartyRecordAdjustSaveDto.class);
        saveDto.setDocumentId(documentId);
        //变更的当事人对应的信息
        List<WorkFlowRollSubMainInfoAndRecordAdjustDto> adjustDtoList=new ArrayList<>();
        //2、处理当事人信息
        dealAdjustPartyRecordForAdjustRecord(saveDto , adjustDtoList);
        //3、处理宽表、详情表案件基本信息
        dealAdjustPartyRecordForCaseBasicInfo(caseId,saveDto);
        //4、撤销案件调查终结报告
        caseDocumentRecordService.updateWithdrawCaseDocumentRecordForAdjust(caseId);
        // 5、处理工作流
        workFlowRollSubMainInfoService.doModWorkFlowRollSubMainInfoAndRecordWithNew(adjustDtoList);
        //6、同步更新证据库当事人信息
        try {
            evidenceInventoryService.updateCpInfo(caseId);
        } catch (Exception e) {
            log.info("调整dan当事人证据库更新当事人失败:{}", e.getMessage());
        }
        if (1 == 1) {
            try {
                //调整当事人同步到取证端
                evidenceInventoryService.saveEvent(caseId, caseMainInfo.getCaseNumber());
            }catch (Exception e){
                e.printStackTrace();
            }

            //当事人更新成功后，生成一条记录，然后定时重新上报已经上报成功的数据
            caseDataChangeReportRecordService.save(caseId, CaseChangeOperationTypeEnum.OPERATION_TYPE_1.getCode(), String.valueOf(userInfo.getUserId()));
            return Constant.INTEGER_1;
        } else {
         //   log.warn("saveCount:{},insertCount:{}", saveCount, insertCount);
            throw new BusinessException("更新当事人信息时出现异常");
        }

    }

    @Override
    public boolean isExistUndoneAdjustPartyRecord(String caseId) {
        boolean flag =false;
        CaseDocumentRecordDto caseDocumentRecordDto = caseDocumentRecordService.getCaseDocumentRecordByKindCode(caseId, DocumentKindEnum.DOC_KIND_DK1TZDSRNBSPB.getCode());
        //校验是否有未完成的调整当事人申请
        if (ObjectUtil.isNotEmpty(caseDocumentRecordDto) && !DocumentStatusEnum.CHECK_END.getCode().equals(caseDocumentRecordDto.getDocumentApprovalStatus())){
            flag =true;
        }

        return flag;
    }

    @Override
    public CasePartyRecordAdjustSaveDto getAdjustPartyRecordDetail(AdjustPartyRecordDetailQueryDto queryDto) {
        String caseId= queryDto.getCaseId();
        CaseDocumentRecordDto caseDocumentRecordDto =new CaseDocumentRecordDto() ;
        if (ObjectUtil.isNotEmpty(queryDto.getDocumentId())){
            CaseDocumentRecordVo caseDocumentRecordVo=caseDocumentRecordService.getCaseDocumentRecordInfo(queryDto.getDocumentId());
            BeanUtils.copyProperties(caseDocumentRecordVo,caseDocumentRecordDto);
        }else {
            caseDocumentRecordService.getCaseDocumentRecordByKindCode(queryDto.getCaseId(), DocumentKindEnum.DOC_KIND_DK1TZDSRNBSPB.getCode());
        }

        CasePartyRecordAdjustSaveDto saveDto =new CasePartyRecordAdjustSaveDto();
        if (ObjectUtil.isNotEmpty(caseDocumentRecordDto) && ObjectUtil.isNotEmpty(caseDocumentRecordDto.getId())){
            JSONObject jsonObj = JSONObject.parseObject(caseDocumentRecordDto.getDocumentContent());
            saveDto = jsonObj.toJavaObject(CasePartyRecordAdjustSaveDto.class);
            saveDto.setDocumentCatalogCode(caseDocumentRecordDto.getDocumentCatalogCode());
            saveDto.setCaseId(caseId);
            saveDto.setDocumentId(caseDocumentRecordDto.getId());

        }else {
            CaseMainInfoVo caseMainInfo = caseMainInfoService.getCaseMainInfo(caseId);
            CaseMainDetailInfo caseMainDetailInfo = caseMainDetailInfoMapper.selectByPrimaryKey(queryDto.getCaseId());
            SysDepartParam sysDepartParam= sysDepartParamService.getSysDepartParamByOrgCode(caseMainInfo.getCaseOrgCode(), caseMainInfo.getCaseDeptCode());
            saveDto.setAuditItem("调整当事人");
            saveDto.setCaseId(caseId);
            saveDto.setCaseConciseCondition(caseMainDetailInfo.getCaseConciseCondition());
            saveDto.setCaseNameAndNumber(caseMainInfo.getCaseName()+caseMainInfo.getCaseNumber());
            saveDto.setOrgStandardName(sysDepartParam.getOrgStandardName());
            saveDto.setPartiesLegalInfoList(casePartiesLegalInfoMapper.selectCasePartiesLegalInfoDtoByCaseId(caseId));
            saveDto.setPartiesPersonInfoList(casePartiesRecordService.getCasePartiesLegalInfoDtoByCaseId(caseId));
            ConfigBusiParamDocumentInfo documentInfoByDocumentKindCode = configBusiParamDocumentInfoService.getDocumentInfoByDocumentKindCode(caseMainInfo.getBusiParamId(), DocumentKindEnum.DOC_KIND_DK1TZDSRNBSPB.getCode());
            saveDto.setDocumentCatalogCode(documentInfoByDocumentKindCode.getDocumentCatalogCode());
        }

        return saveDto;
    }

    /**
     * 描述：更新案件名称等信息
     *
     * @param caseId 案件id
     * @return int
     * @author shishengyao
     * @date 2023/03/23
     */
    @Transactional(rollbackFor = {Error.class, Exception.class})
    public int dealAdjustPartyRecordForCaseBasicInfo(String caseId,CasePartyRecordAdjustSaveDto saveDto) {
        //后台自动生成案件名称
        //去除案由中的“对”和“的行政处罚”
        //多当事人  `${party}等${partyCount}个当事人涉嫌${resetReason}案`
        //多案由    `${party}涉嫌${resetReason}等${caseLen}项违法行为案`
        //单当事人  `${party}涉嫌${resetReason}案`
        CaseMainInfo caseMainInfo = new CaseMainInfo();
        //获取当事人信息
        List<CasePartiesRecordVo> casePartiesInfoList = casePartiesRecordService.getCasePartiesInfo(caseId);
        CasePartiesRecordVo theFirstPartyInfo = casePartiesInfoList.get(Constant.INTEGER_0);
        String partyShowName = theFirstPartyInfo.getPartyName();
        int partyNum = casePartiesInfoList.size();
        if (partyNum > 1) {
            partyShowName += "等" + partyNum + "个当事人";
            caseMainInfo.setCasePartiesReasonType(PartiesReasonTypeEnum.MULTIPLE_PARTIES.getCode());
        }

        //获取案由信息
        String caseReasonName = "";
        Example example = new Example(CaseReasonMainRecord.class);
        example.createCriteria().andEqualTo("caseId", caseId).andEqualTo("status", Constant.STRING_1);
        List<CaseReasonMainRecord> caseReasonMainRecords = caseReasonMainRecordMapper.selectByExample(example);
        if (!ObjectUtils.isEmpty(caseReasonMainRecords)) {
            if (caseReasonMainRecords.size() == 1) {
                caseReasonName = BaseUtil.handleCaseReason(caseReasonMainRecords.get(0).getCaseReasonName() + "案");
                if (partyNum==1){
                    caseMainInfo.setCasePartiesReasonType(PartiesReasonTypeEnum.SINGLE_PARTY.getCode());
                }
            } else {
                caseReasonName = BaseUtil.handleCaseReason(caseReasonMainRecords.get(0).getCaseReasonName()) + "等" + caseReasonMainRecords.size() + "项违法行为案";
                caseMainInfo.setCasePartiesReasonType(PartiesReasonTypeEnum.MULTIPLE_REASONS.getCode());
            }
        }
        // 人社案由
        if (Constant.HUMAN_SOCIETY_BARS_CODE.equals(caseMainInfo.getLineCode())) {
            CaseMainDetailInfo caseMainDetailInfo = caseMainDetailInfoMapper.selectByPrimaryKey(caseMainInfo.getId());
            caseReasonName=caseMainDetailInfo.getPersonReasonName()+ "案";
        }
        //应急案由
        if(TerritoryCodeEnum.YJGL.getCode().equals(caseMainInfo.getLineCode())){
            CaseMainDetailInfo caseMainDetailInfo = caseMainDetailInfoMapper.selectByPrimaryKey(caseMainInfo.getId());
            String caseEmergencyReasonContent = caseMainDetailInfo.getCaseEmergencyReasonContent();
            List<CaseEmergencyReasonInfoDto> list = JSON.parseArray(caseEmergencyReasonContent, CaseEmergencyReasonInfoDto.class);
            List<String> reasonNameList = CollUtil.newArrayList();
            list.forEach( u -> reasonNameList.add(u.getEmergencyReasonName()));
            caseReasonName=CollUtil.join(reasonNameList, "&") + "案";
        }

        String newCaseName = partyShowName + "涉嫌" + caseReasonName;
        int count;
        caseMainInfo.setId(caseId);
        caseMainInfo.setCaseName(newCaseName);
        caseMainInfo.setHandleType("");
        count = caseMainInfoMapper.updateByPrimaryKeySelective(caseMainInfo);

        CaseMainDetailInfo caseMainDetailInfo = new CaseMainDetailInfo();
        caseMainDetailInfo.setCaseId(caseId);
        caseMainDetailInfo.setCaseName(newCaseName);
        caseMainDetailInfo.setHandleConclusion("");
        caseMainDetailInfo.setPunishOpinion("");
        caseMainDetailInfo.setPunishKinds("");
        caseMainDetailInfo.setDraftPunishMoney("");
        caseMainDetailInfo.setIsImportantCase("");
        caseMainDetailInfo.setIsNeedCollectiveDiscuss("");
        caseMainDetailInfo.setInvestConclusion("");
        caseMainDetailInfo.setCaseConciseCondition(saveDto.getCaseConciseCondition());
        caseMainDetailInfoMapper.updateByPrimaryKeySelective(caseMainDetailInfo);
        return count;
    }

    /**
     * 描述：保存补充表
     *
     * @param caseId       用例id
     * @param partyId      方id
     * @param operateType  操作类型
     * @param caseMainInfo 案例主要信息
     * @return int
     * @author shishengyao
     * @date 2023/03/28
     */
    @Transactional(rollbackFor = Exception.class)
    public int  dealSaveCaseMainDetailAuxiliary(String caseId ,String partyId , String operateType,CaseMainInfoVo caseMainInfo){

        UserDTO userInfo=UserUtil.getUserInfo();
        Example example = new Example(CaseMainDetailAuxiliaryInfo.class);
        example.createCriteria().andEqualTo("caseId", caseId).andEqualTo("partyId",partyId);
        int count = 0;
        //将变更的记录保存到 数据处理-操作日志表-案件详情补充表
        List<CaseMainDetailAuxiliaryInfo> caseMainDetailAuxiliaryInfos = caseMainDetailAuxiliaryInfoMapper.selectByExample(example);
        //历史记录添加进数据处理-补充表数据中
        if (ObjectUtil.isNotEmpty(caseMainDetailAuxiliaryInfos) && caseMainDetailAuxiliaryInfos.size()>0){
            caseMainDetailAuxiliaryInfos.forEach(e->{
                DataProcessCaseMainDetailAuxiliaryInfo dataProcessCaseMainDetailAuxiliaryInfo=new DataProcessCaseMainDetailAuxiliaryInfo();
                BeanUtils.copyProperties(e,dataProcessCaseMainDetailAuxiliaryInfo);
                dataProcessCaseMainDetailAuxiliaryInfo.setId(BaseUtil.createUid());
                dataProcessCaseMainDetailAuxiliaryInfo.setRecordId(e.getId());
                dataProcessCaseMainDetailAuxiliaryInfo.setOperateSource("S001");
                dataProcessCaseMainDetailAuxiliaryInfo.setOperateUserId(userInfo.getUserId()+"");
                dataProcessCaseMainDetailAuxiliaryInfo.setOperateTime(LocalDateTime.now());
                if (RecordSaveTypeEnum.DEL.getCode().equals(operateType)){
                    dataProcessCaseMainDetailAuxiliaryInfo.setOperateType("delete");
                }else if (RecordSaveTypeEnum.MOD.getCode().equals(operateType)){
                    dataProcessCaseMainDetailAuxiliaryInfo.setOperateType("modify");
                }
                dataProcessCaseMainDetailAuxiliaryInfoMapper.insertSelective(dataProcessCaseMainDetailAuxiliaryInfo);
            });
        }
        //删除当事人
        if (RecordSaveTypeEnum.DEL.getCode().equals(operateType)){
            count= caseMainDetailAuxiliaryInfoMapper.deleteByExample(example);
        }
        CaseMainDetailAuxiliaryInfo auxiliaryInfo = new CaseMainDetailAuxiliaryInfo();
        //变更当事人
        if (RecordSaveTypeEnum.MOD.getCode().equals(operateType)){
            CasePartiesRecordVo casePartiesInfoVo = casePartiesRecordService.getCasePartiesInfoByPartyId(caseId, partyId);
            auxiliaryInfo.setPartyId(casePartiesInfoVo.getPartyId());
            auxiliaryInfo.setPartyName(casePartiesInfoVo.getPartyName());
            auxiliaryInfo.setCaseId(caseId);
            count=   caseMainDetailAuxiliaryInfoMapper.updateByExampleSelective(auxiliaryInfo,example);
        }
        //新增当事人
        if (RecordSaveTypeEnum.ADD.getCode().equals(operateType)){
            CasePartiesRecordVo casePartiesInfoVo = casePartiesRecordService.getCasePartiesInfoByPartyId(caseId, partyId);
            List<CaseReasonMainRecordVo> caseReasonMainRecordVoList = caseReasonMainRecordService.getCaseReasonRecordListByCaseId(caseId);
            //多案由插入多条数据
            if (PartiesReasonTypeEnum.MULTIPLE_REASONS.getCode().equals(caseMainInfo.getCasePartiesReasonType()) ){
                for (CaseReasonMainRecordVo vo : caseReasonMainRecordVoList){
                    auxiliaryInfo.setId(BaseUtil.createUid());
                    auxiliaryInfo.setCaseId(caseMainInfo.getId());
                    auxiliaryInfo.setCaseReasonId(vo.getId());
                    auxiliaryInfo.setCaseReasonName(vo.getCaseReasonName());
                    auxiliaryInfo.setPartyId(casePartiesInfoVo.getPartyId());
                    auxiliaryInfo.setPartyName(casePartiesInfoVo.getPartyName());
                    caseMainDetailAuxiliaryInfoMapper.insertSelective(auxiliaryInfo);
                }
            }else {
                if(ObjectUtil.isNotEmpty(caseReasonMainRecordVoList) && caseReasonMainRecordVoList.size()>0){
                    auxiliaryInfo.setCaseReasonId(caseReasonMainRecordVoList.get(0).getId());
                    auxiliaryInfo.setCaseReasonName(caseReasonMainRecordVoList.get(0).getCaseReasonName());
                }
                auxiliaryInfo.setId(BaseUtil.createUid());
                auxiliaryInfo.setCaseId(caseMainInfo.getId());
                auxiliaryInfo.setPartyId(casePartiesInfoVo.getPartyId());
                auxiliaryInfo.setPartyName(casePartiesInfoVo.getPartyName());
                caseMainDetailAuxiliaryInfoMapper.insertSelective(auxiliaryInfo);
            }

        }
        return count;
    }

    /**
     * 描述：校验调整当事人参数
     *
     * @param caseMainInfo 案例主要信息
     * @param saveDto      保存dto
     * @return {@link String }
     * @author shishengyao
     * @date 2023/03/27
     */
    @Override
    public String checkAndAssembleAdjustPartyRecordParam(CaseMainInfoVo caseMainInfo, CasePartyRecordAdjustSaveDto saveDto) {
        String errorMsg = "";
        if (!CaseStageEnum.INVESTIGATION.getCode().equals(caseMainInfo.getCaseCurrentStageCode())) {
            return "非调查取证环节不可调整当事人";
        }
        //案件案由、当事人类型；1：单案由单当事人 2：多案由单当事人 3：单案由多当事人
        String casePartiesReasonType = caseMainInfo.getCasePartiesReasonType();
        //法人当事人数量
        int partiesLegalCount = ObjectUtil.isEmpty(saveDto.getPartiesLegalInfoList()) ? 0 : saveDto.getPartiesLegalInfoList().size();
        //个人当事人数量
        int partiesPersonCount = ObjectUtil.isEmpty(saveDto.getPartiesPersonInfoList()) ? 0 : saveDto.getPartiesPersonInfoList().size();
        //当事人总数
        int partiesCount = partiesLegalCount + partiesPersonCount;
        if (PartiesReasonTypeEnum.MULTIPLE_REASONS.getCode().equals(casePartiesReasonType) && partiesCount > 1) {
            return "多案由只允许有一个当事人，不可新增当事人";
        }
        //2、校验当事人信息
        if (partiesLegalCount > 1) {
            return "企业当事人只能有一个";
        }
        if (partiesCount < 1) {
            return  "必须选择至少一个当事人";
        } else if (partiesCount > 10) {
            return "当事人不能超过10个";
        }
        saveDto.setCasePartiesReasonType(casePartiesReasonType);
        List<CasePartyRecordAdjustPersonSaveDto> partiesPersonInfoForPdfList = new ArrayList<>();
        //4、校验法人当事人信息的合法性
        List<CasePartyRecordAdjustLegalSaveDto> partiesLegalInfoDtos = saveDto.getPartiesLegalInfoList();
        if (partiesLegalCount > 0) {
            List<CasePartyRecordAdjustLegalSaveDto> partiesLegalInfoForPdfList = new ArrayList<>();
            for (CasePartyRecordAdjustLegalSaveDto legalInfoDto : partiesLegalInfoDtos) {
                if (!SocialCreditCodeUtil.isValidEntCode(legalInfoDto.getUniscid(),legalInfoDto.getEntType())){
                    return "统一社会信用代码：" + legalInfoDto.getUniscid() + "不符合规范";
                }
                if (caseMainInfo.getLineCode().contains(TerritoryCodeEnum.NYNC.getCode())
                        && EnterTypeEnum.PRIVATELY_BUSINESS.getCode().equals(legalInfoDto.getEntType())) {
                    //农业农村个体工商户信息放在个人列表中
                    String certType =CertTypeEnum.getValueByCode(legalInfoDto.getLegalCertType());
                    CasePartyRecordAdjustPersonSaveDto partiesPersonInfoForPdf = new CasePartyRecordAdjustPersonSaveDto();
                    partiesPersonInfoForPdf.setCertType(certType);
                    partiesPersonInfoForPdf.setCertNo(legalInfoDto.getLegalCertNo());
                    partiesPersonInfoForPdf.setSex("/");
                    partiesPersonInfoForPdf.setBirth("/");
                    partiesPersonInfoForPdf.setNationality("/");
                    partiesPersonInfoForPdf.setAddress(legalInfoDto.getUnitAddress());
                    partiesPersonInfoForPdf.setName(legalInfoDto.getLegal());
                    partiesPersonInfoForPdf.setMobile(ObjectUtils.isEmpty(legalInfoDto.getPhone()) ? "/" : legalInfoDto.getPhone());
                    partiesPersonInfoForPdf.setUnitName(legalInfoDto.getEntName());
                    partiesPersonInfoForPdf.setPostCode(BaseUtil.transferNullToSlash(legalInfoDto.getPostCode()));
                    partiesPersonInfoForPdf.setUniscid(ObjectUtils.isEmpty(legalInfoDto.getUniscid()) ? "/" : legalInfoDto.getUniscid());
                    String workAndJob = legalInfoDto.getEntName() + (ObjectUtils.isEmpty(legalInfoDto.getJob()) ? "" : " " + legalInfoDto.getJob());
                    partiesPersonInfoForPdf.setUnitNameAndJob(workAndJob);
                    partiesPersonInfoForPdfList.add(partiesPersonInfoForPdf);
                } else {
                    CasePartyRecordAdjustLegalSaveDto partiesLegalInfoForPdf =new CasePartyRecordAdjustLegalSaveDto();
                    BeanUtil.copyProperties(legalInfoDto,partiesLegalInfoForPdf);
                    partiesLegalInfoForPdf.setPhone(ObjectUtils.isEmpty(legalInfoDto.getPhone()) ? "/" : legalInfoDto.getPhone());
                    partiesLegalInfoForPdf.setJob(ObjectUtils.isEmpty(legalInfoDto.getJob()) ? "/" : legalInfoDto.getJob());
                    partiesLegalInfoForPdf.setLegalCertNo(ObjectUtils.isEmpty(legalInfoDto.getLegalCertNo()) ? "/" : legalInfoDto.getLegalCertNo());
                    partiesLegalInfoForPdf.setPostCode(BaseUtil.transferNullToSlash(legalInfoDto.getPostCode()));
                    partiesLegalInfoForPdf.setEntAddress(BaseUtil.transferNullToSlash(legalInfoDto.getAddress()));
                    partiesLegalInfoForPdfList.add(partiesLegalInfoForPdf);
                }

            }
            saveDto.setPartiesLegalInfoForPdfList(partiesLegalInfoForPdfList);
        }

        //5、校验个人当事人信息的合法性
        List<CasePartyRecordAdjustPersonSaveDto> partiesPersonInfoList = saveDto.getPartiesPersonInfoList();
        if (partiesPersonCount > 0) {
            //判断是否有重复用户
            Map<Object, Long> personInfoCollect = partiesPersonInfoList.stream().collect(
                    Collectors.groupingBy(CasePartyRecordAdjustPersonSaveDto::getCertNo, Collectors.counting()));
            List<Object> repeatCertNos = personInfoCollect.keySet().stream().
                    filter(key -> personInfoCollect.get(key) > 1).collect(Collectors.toList());
            if (ObjectUtil.isNotEmpty(repeatCertNos) && repeatCertNos.size() > 0) {
                String collect = repeatCertNos.stream().map(e -> e.toString()).collect(Collectors.joining(","));
                errorMsg = "当事人证件号" + collect + "重复";
                return errorMsg;
            }
            for (CasePartyRecordAdjustPersonSaveDto personSaveDto : partiesPersonInfoList) {
                CasePartyRecordAdjustPersonSaveDto partiesPersonInfoForPdf = new CasePartyRecordAdjustPersonSaveDto();
                BeanUtils.copyProperties(personSaveDto,partiesPersonInfoForPdf);
                //校验身份证是否合法
                if (org.apache.commons.lang.StringUtils.isNotEmpty(partiesPersonInfoForPdf.getCertNo()) && partiesPersonInfoForPdf.getCertType().equals("SFZ")) {
                    boolean flag = commonService.checkRealNameDifferent(partiesPersonInfoForPdf.getCertNo(), partiesPersonInfoForPdf.getName());
                    if (flag) {
                        errorMsg = "当事人" + partiesPersonInfoForPdf.getName() + "证件号码和姓名不匹配";
                        return errorMsg;
                    }
                }
                String certType =CertTypeEnum.getValueByCode(partiesPersonInfoForPdf.getCertType());
                partiesPersonInfoForPdf.setCertType(certType);
                partiesPersonInfoForPdf.setCertNo(partiesPersonInfoForPdf.getCertNo());
                partiesPersonInfoForPdf.setMobile(BaseUtil.transferNullToSlash(partiesPersonInfoForPdf.getMobile()));
                partiesPersonInfoForPdf.setUnitName(BaseUtil.transferNullToSlash(partiesPersonInfoForPdf.getUnitName()));
                partiesPersonInfoForPdf.setPostCode(BaseUtil.transferNullToSlash(partiesPersonInfoForPdf.getPostCode()));
                partiesPersonInfoForPdf.setAddress(personSaveDto.getAddress());
                partiesPersonInfoForPdf.setUniscid("/");
                if (ObjectUtils.isEmpty(partiesPersonInfoForPdf.getUnitName())) {
                    partiesPersonInfoForPdf.setUnitNameAndJob("/");
                } else {
                    partiesPersonInfoForPdf.setUnitNameAndJob(partiesPersonInfoForPdf.getUnitName());
                }
                partiesPersonInfoForPdfList.add(partiesPersonInfoForPdf);
            }
           saveDto.setPartiesPersonInfoForPdfList(partiesPersonInfoForPdfList);
        }

        return errorMsg;
    }

    /**
     * 描述：处理调整当事人，文书记录信息
     *
     * @param saveDto       保存dto
     * @param adjustDtoList 调整dto列表
     * @author shishengyao
     * @date 2023/03/29
     */
    @Transactional(rollbackFor = {Error.class, Exception.class})
    public void dealAdjustPartyRecordForAdjustRecord(CasePartyRecordAdjustSaveDto saveDto , List<WorkFlowRollSubMainInfoAndRecordAdjustDto> adjustDtoList) {
        UserDTO userInfo= UserUtil.getUserInfo();
        String caseId =saveDto.getCaseId();
        CaseMainInfoVo caseMainInfo = caseMainInfoService.getCaseMainInfo(caseId);
        List<CasePartyRecordAdjustLegalSaveDto> partiesLegalInfoList = saveDto.getPartiesLegalInfoList();
        List<CasePartyRecordAdjustPersonSaveDto> partiesPersonInfoList = saveDto.getPartiesPersonInfoList();

        CaseInfoAdjustRecordDto caseInfoAdjustRecordDto = new CaseInfoAdjustRecordDto();
        caseInfoAdjustRecordDto.setCaseId(caseId);

        //调整之前的信息记录
        List<String> itemCodeBeforeAdjustList = new  ArrayList<>();
        List<String> itemCodeAfterAdjustList  = new  ArrayList<>();
        List<String> itemShowInfoBeforeAdjustList  = new  ArrayList<>();
        List<String> itemShowInfoAfterAdjustList  = new  ArrayList<>();
        List<CasePartiesInfoVo> beforePartiesList = casePartiesRecordService.getCasePartiesInfoList(new CasePartiesRecordQueryDto(caseId, null,YesOrNoEnum.NO.getCode()));
        beforePartiesList.forEach(e->{
            itemCodeBeforeAdjustList.add(e.getId());
            String tmpStr="";
            if(PartyTypeEnum.PERSON.getCode().equals(e.getPartyType())){
                tmpStr = "姓名："+e.getPartyName()+" 证件号码："+e.getPartyIdentityCode()+" 联系电话："+e.getContactPhone()+" 住址："+e.getAddress()+" 工作单位："+e.getWorkUnitName();
            } else {
                tmpStr = "单位名称："+e.getPartyName()+" 法定代表人姓名："+e.getLegalName()+" 统一社会信用代码："+e.getPartyIdentityCode()+" 注册地址："+e.getAddress();
            }
            itemShowInfoBeforeAdjustList.add(tmpStr);
        });

        //获取存在的当事人Id
        List<String> existPartyIds=new ArrayList<>();
        //2、法人信息处理
        for (CasePartyRecordAdjustLegalSaveDto casePartiesLegalInfoDto : partiesLegalInfoList){
            boolean isChange = true;
            CasePartiesRecord record = casePartiesRecordService.getCasePartiesRecordByIdentityCode(caseId,casePartiesLegalInfoDto.getUniscid(),PartyTypeEnum.LEGAL.getCode(),null);
            boolean isExistPartyId = checkIsExistPartyRecord(record);
            String partyIdUuid = "";
            if (isExistPartyId){
                partyIdUuid = record.getPartyId();
                CasePartiesLegalInfo casePartiesLegalInfo =new CasePartiesLegalInfo();
                BeanUtils.copyProperties(casePartiesLegalInfoDto,casePartiesLegalInfo);
                if (casePartiesLegalInfoMapper.select(casePartiesLegalInfo).size()>0){
                    isChange=false;
                }
            }else {
                partyIdUuid=BaseUtil.createUid();
            }
            // 有变更添加
            if (isChange){
                String operateType = isExistPartyId ? RecordSaveTypeEnum.MOD.getCode() : RecordSaveTypeEnum.ADD.getCode();
                //保存当事人信息
                casePartiesLegalInfoDto.setCaseId(caseId);
                casePartiesLegalInfoDto.setId(partyIdUuid);
                casePartiesLegalInfoDto.setPartyId(partyIdUuid);
                casePartiesLegalInfoDto.setOperateType(operateType);
                casePartiesLegalInfoDto.setIsQueryInvalidData(YesOrNoEnum.YES.getCode());
                casePartiesLegalInfoDto.setLegalIndustryType(casePartiesLegalInfoDto.getLegalIndustryType());
                //更新当事人信息
                String partyId=   casePartiesLegalInfoService.saveCasePartiesLegalInfoWithAdjust(casePartiesLegalInfoDto);
                // 保存补充表
                dealSaveCaseMainDetailAuxiliary(caseId,partyIdUuid,operateType,caseMainInfo);
                WorkFlowRollSubMainInfoAndRecordAdjustDto adjustDto =new  WorkFlowRollSubMainInfoAndRecordAdjustDto();
                adjustDto.setWorkId(caseId);
                adjustDto.setNewWorkSubId(partyIdUuid);
                adjustDto.setOldWorkSubId(isExistPartyId ? partyIdUuid : null);
                adjustDtoList.add(adjustDto);
                //添加有效的partyId
                existPartyIds.add(partyId);
            }else {
                existPartyIds.add(partyIdUuid);
            }
        }
        //3、个人信息处理
        for (CasePartyRecordAdjustPersonSaveDto personInfoDto : partiesPersonInfoList){
            boolean isChange = true;
            CasePartiesRecord record = casePartiesRecordService.getCasePartiesRecordByIdentityCode(caseId,personInfoDto.getCertNo(),PartyTypeEnum.PERSON.getCode(),personInfoDto.getCertType());
            boolean isExistPartyId = checkIsExistPartyRecord(record);
            String partyIdUuid ="";
            if (isExistPartyId){
                partyIdUuid=record.getPartyId();
                CasePartiesPersonInfo casePartiesPersonInfo =new CasePartiesPersonInfo();
                BeanUtils.copyProperties(personInfoDto,casePartiesPersonInfo);
                if (casePartiesPersonInfoMapper.select(casePartiesPersonInfo).size()>0){
                    isChange=false;
                }
            }else {
                partyIdUuid=BaseUtil.createUid();
            }

            if (isChange){
                String operateType = isExistPartyId ? RecordSaveTypeEnum.MOD.getCode() : RecordSaveTypeEnum.ADD.getCode();
                personInfoDto.setCaseId(caseId);
                personInfoDto.setId(partyIdUuid);
                personInfoDto.setPartyId(partyIdUuid);
                personInfoDto.setCaseId(caseId);
                personInfoDto.setIsQueryInvalidData(YesOrNoEnum.YES.getCode());
                personInfoDto.setOperateType(operateType);
                personInfoDto.setAddress(personInfoDto.getAddress());
                String partyId = casePartiesPersonInfoService.saveCasePartiesPersonInfoWithAdjust(personInfoDto);
                //添加有效的partyId
                existPartyIds.add(partyId);
                //处理案件补充表
                dealSaveCaseMainDetailAuxiliary(caseId,partyIdUuid,operateType,caseMainInfo);
                //添加进工作流
                WorkFlowRollSubMainInfoAndRecordAdjustDto adjustDto =new  WorkFlowRollSubMainInfoAndRecordAdjustDto();
                adjustDto.setWorkId(caseId);
                adjustDto.setNewWorkSubId(partyIdUuid);
                adjustDto.setOldWorkSubId(isExistPartyId ? partyIdUuid : null);
                adjustDtoList.add(adjustDto);
            }else {
                existPartyIds.add(partyIdUuid);
            }
        }
        // 删除当事人记录表
        List<String> deletePartyIds = casePartiesRecordMapper.selectDeletePartyIds(existPartyIds,caseId);
        for (String deletePartyId : deletePartyIds){
            WorkFlowRollSubMainInfoAndRecordAdjustDto adjustDto =new  WorkFlowRollSubMainInfoAndRecordAdjustDto();
            adjustDto.setWorkId(caseId);
            adjustDto.setOldWorkSubId(deletePartyId);
            adjustDtoList.add(adjustDto);
            // 删除当事人
            casePartiesRecordService.delCasePartiesRecordByPartyId(deletePartyId);
            //文书作废
            caseDocumentRecordService.saveInvalidCaseDocumentRecordByPartyIdForAdjust(caseId,deletePartyId);
            // 保存补充表
            CasePartiesRecordDto casePartiesRecordDto = new CasePartiesRecordDto();
            casePartiesRecordDto.setCaseId(caseId);
            casePartiesRecordDto.setPartyId(deletePartyId);
            //删除补充表
            dealSaveCaseMainDetailAuxiliary(caseId,deletePartyId,RecordSaveTypeEnum.DEL.getCode(),caseMainInfo);
        }

        //调整后当事人信息
        List<CasePartiesInfoVo>  afterCasePartiesList = casePartiesRecordService.getCasePartiesInfoList(new CasePartiesRecordQueryDto(caseId, null,YesOrNoEnum.NO.getCode()));
        afterCasePartiesList.forEach(e->{
            itemCodeAfterAdjustList.add(e.getId());
            String tmpStr="";
            if(PartyTypeEnum.PERSON.getCode().equals(e.getPartyType())){
                tmpStr = "姓名："+e.getPartyName()+" 证件号码："+e.getPartyIdentityCode()+" 联系电话："+e.getContactPhone()+" 住址："+e.getAddress()+" 工作单位："+e.getWorkUnitName();
            } else {
                tmpStr = "单位名称："+e.getPartyName()+" 法定代表人姓名："+e.getLegalName()+" 统一社会信用代码："+e.getPartyIdentityCode()+" 注册地址："+e.getAddress();
            }
            itemShowInfoAfterAdjustList.add(tmpStr);
        });
        //保存调整记录
        caseInfoAdjustRecordDto.setOperateType(RecordSaveTypeEnum.ADD.getCode());
        caseInfoAdjustRecordDto.setAdjustType(CaseInfoAdjustTypeEnum.PARTY.getCode());
        caseInfoAdjustRecordDto.setItemCodeAfterAdjust(String.join(";",itemCodeAfterAdjustList ));
        caseInfoAdjustRecordDto.setItemCodeBeforeAdjust(String.join(";",itemCodeBeforeAdjustList ));
        caseInfoAdjustRecordDto.setItemShowInfoAfterAdjust(String.join(";",itemShowInfoAfterAdjustList ));
        caseInfoAdjustRecordDto.setItemShowInfoBeforeAdjust(String.join(";",itemShowInfoBeforeAdjustList ));
        caseInfoAdjustRecordDto.setAttachmentInfo(saveDto.getAttachmentInfoList());
        caseInfoAdjustRecordDto.setAdjustUserId(userInfo.getUserId() + "");
        caseInfoAdjustRecordDto.setAdjustUserName(userInfo.getRealName());
        caseInfoAdjustRecordDto.setDocumentId(saveDto.getDocumentId());
        caseInfoAdjustRecordDto.setAdjustReason(saveDto.getAuditReason());
        saveCaseInfoAdjustRecord(caseInfoAdjustRecordDto);
    }

    /**
     * 描述：是否存在当事人记录
     *
     * @return boolean
     * @author shishengyao
     * @date 2023/03/29
     */
    private boolean checkIsExistPartyRecord(CasePartiesRecord record){
        // 当事人证件变更就认为是修改了一个当事人
        boolean isExistPartyId = false;
        if (ObjectUtil.isNotEmpty(record) && ObjectUtil.isNotEmpty(record.getId())){
            isExistPartyId=true;
        }
        return isExistPartyId;
    }

}
